package com.example.springbootquartz.config;

import com.example.springbootquartz.job.MyJob;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

@Configuration
public class MyJobQuartzConfig {

    @Bean("jobDetailFactoryBeanByMyJob")
    public JobDetailFactoryBean jobDetailFactoryBean(){
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        //指定具体的job类
        jobDetailFactoryBean.setJobClass(MyJob.class);
        //指定job的名称
        jobDetailFactoryBean.setName("myJob");
        //指定job的分组
        jobDetailFactoryBean.setGroup("jobs");
        //必须设置为true，如果为false，当没有活动的触发器与之关联时会在调度器中删除该任务
        jobDetailFactoryBean.setDurability(true);
        //指定spring容器的key，如果不设定在job中的jobmap中是获取不到spring容器的(可以自定义key值)
//        jobDetailFactoryBean.setApplicationContextJobDataKey("abc");
        return jobDetailFactoryBean;
    }

    /**
     * 定义触发器
     * @return
     */
    @Bean("cronTriggerFactoryBeanByMyJob")
    public CronTriggerFactoryBean cronTriggerFactoryBean(@Qualifier("jobDetailFactoryBeanByMyJob") JobDetailFactoryBean jobDetailFactoryBean){
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        //触发的时间频率(5s执行一次)
        cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?");
        return cronTriggerFactoryBean;
    }

    /**
     *
     * 测试一个job绑定多个触发
     *
     * 定义触发器
     * @return
     */
    @Bean("cronTriggerFactoryBean2ByMyJob")
    public CronTriggerFactoryBean cronTriggerFactoryBean2(@Qualifier("jobDetailFactoryBeanByMyJob") JobDetailFactoryBean jobDetailFactoryBean){
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        //触发的时间频率(12s执行一次)
        cronTriggerFactoryBean.setCronExpression("0/12 * * * * ?");
        return cronTriggerFactoryBean;
    }

    /**
     * 定义调度器
     * @return
     */
    @Bean("schedulerFactoryBeanByMyJob")
    public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("cronTriggerFactoryBeanByMyJob") CronTriggerFactoryBean cronTriggerFactoryBean,
                                                     @Qualifier("cronTriggerFactoryBean2ByMyJob") CronTriggerFactoryBean cronTriggerFactoryBean2){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        schedulerFactoryBean.setTriggers(cronTriggerFactoryBean.getObject(), cronTriggerFactoryBean2.getObject());
        return schedulerFactoryBean;
    }
}
